package net.xo68.destiny.manager.security;


import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.user.ISystemUser;
import net.xo68.destiny.core.jwt.JwtClaimsBuilder;
import net.xo68.destiny.core.jwt.JwtTokenParser;
import net.xo68.destiny.core.jwt.JwtTokenTemplate;
import net.xo68.destiny.starter.manager.SchedulerManagerProperties;
import org.springframework.stereotype.Component;

/**
 * 用户jwt操作模板
 */
@Slf4j
@Component
public class UserJwtTokenTemplate {

    public static final String CLAIM_NAME_NICE="nice";
    public static final String CLAIM_NAME_ROLES="roles";
    public static final String CLAIM_NAME_SEX="sex";
    public static final String CLAIM_NAME_STATE="state";

    private final JwtTokenTemplate jwtTokenTemplate;
    private final SchedulerManagerProperties schedulerManagerProperties;

    public UserJwtTokenTemplate(SchedulerManagerProperties schedulerManagerProperties) {
        this.schedulerManagerProperties=schedulerManagerProperties;
        this.jwtTokenTemplate = new JwtTokenTemplate(this.schedulerManagerProperties.getUserTokenSecret(),this.schedulerManagerProperties.getUserTokenIssuer());
    }

    public String token(ISystemUser systemUser){
        return this.jwtTokenTemplate.generateToken(String.valueOf(systemUser.getId()),systemUser.getAccount(),systemUser.getAccount(),
                JwtClaimsBuilder.builder()
                        .put(CLAIM_NAME_NICE,systemUser.getNice())
                        .put(CLAIM_NAME_ROLES,systemUser.getRoles())
                        .put(CLAIM_NAME_SEX,systemUser.getSex())
                        .put(CLAIM_NAME_STATE,systemUser.getUserState())
                        .build(),
                schedulerManagerProperties.getUserTokenExpire().toMinutes()*60L);
    }

    public SecurityUser parse(String token){
        try {
            JwtTokenParser tokenParser=this.jwtTokenTemplate.parse(token);
            if(tokenParser.isExpiration()){
                throw new IllegalArgumentException("token expired");
            }
            SecurityUser securityUser=new SecurityUser();
            securityUser.setId(Long.valueOf(tokenParser.getId()));
            securityUser.setAccount(tokenParser.getSubject());
            securityUser.setNice(tokenParser.get(CLAIM_NAME_NICE,String.class));
            securityUser.setRoles(tokenParser.get(CLAIM_NAME_ROLES,String.class));
            securityUser.setSex(tokenParser.get(CLAIM_NAME_SEX,Integer.class));
            securityUser.setUserState(tokenParser.get(CLAIM_NAME_STATE,Integer.class));
            return securityUser;
        }catch (Exception e){
            log.warn(e.getMessage(),e);
            return null;
        }
    }
}
